package liuliu.throughwaring.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import net.tsz.afinal.annotation.view.CodeNote;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import liuliu.custom.control.dialog.LLDialog;
import liuliu.custom.control.edittext.ImageEditText;
import liuliu.custom.control.edittext.SpinnerEditText;
import liuliu.custom.control.toolbar.TToolbar;
import liuliu.custom.method.Utils;
import liuliu.throughwaring.R;
import liuliu.throughwaring.adapter.CommonAdapter;
import liuliu.throughwaring.adapter.MyViewHolder;
import liuliu.throughwaring.adapter.RecycleAdapter;
import liuliu.throughwaring.adapter.ViewHolder;
import liuliu.throughwaring.base.BaseActivity;
import liuliu.throughwaring.control.add.police.work.IRegTransationView;
import liuliu.throughwaring.control.add.police.work.RegTransactionListener;
import liuliu.throughwaring.model.CodeModel;
import liuliu.throughwaring.model.CompanyModel;
import liuliu.throughwaring.model.PoliceModel;
import liuliu.throughwaring.model.TransactionModel;

/**
 * Created by liuliu on 2015/11/20   16:34
 * 记录检查事务
 *
 * @author 柳伟杰
 */
public class AddWorkActivity extends BaseActivity implements IRegTransationView {
    public static AddWorkActivity mInstance;
    CompanyModel com;
    @CodeNote(id = R.id.reg_work_drawer)
    DrawerLayout right_menu;//右侧菜单
    @CodeNote(id = R.id.right_menu_police_search_ll)
    LinearLayout right_menu_police_search_ll;
    @CodeNote(id = R.id.right_menu_unit_search_ll)
    LinearLayout right_menu_unit_search_ll;
    @CodeNote(id = R.id.right_menu_person_search_ll)
    LinearLayout right_menu_person_search_ll;
    @CodeNote(id = R.id.right_menu_listview)
    ListView mRightMenu;
    @CodeNote(id = R.id.right_menu_search_button)
    Button right_menu_search_button;

    @CodeNote(id = R.id.reg_work_remark_toolbar)
    TToolbar mToolbar;
    @CodeNote(id = R.id.reg_work_remark)
    ImageEditText mRemark;
    @CodeNote(id = R.id.reg_work_image)
    ImageView mImg;
    @CodeNote(id = R.id.reg_word_unit_type, click = "onClick")
    SpinnerEditText reg_word_unit_type;
    @CodeNote(id = R.id.reg_work_companys, click = "onClick")
    SpinnerEditText shearchCompanys;
    @CodeNote(id = R.id.reg_work_camera_btn, click = "onClick")
    Button mCameraBtn;
    @CodeNote(id = R.id.reg_work_reg_btn, click = "onClick")
    Button mRegBtn;
    @CodeNote(id = R.id.right_menu_toolbar)
    TToolbar mRightToolbar;//右侧菜单toolbar
    @CodeNote(id = R.id.right_menu_rv)
    RecyclerView mRightView;//右侧菜单view
    @CodeNote(id = R.id.right_menu_search_button, click = "onClick")
    Button mRightBtn;
    List<CodeModel> mList;
    StringBuffer path = new StringBuffer();
    Bitmap bm = null;
    RegTransactionListener mListener;
    TransactionModel transactionModel;
    String companyType = "Company";
    Dialog dialog;
    CompanyModel companyModel = null;

    @Override
    public void initViews() {
        transactionModel = new TransactionModel();
        Intent intent = getIntent();
        companyModel = (CompanyModel) intent.getSerializableExtra("CompanyModel");
        setContentView(R.layout.activity_reg_work);
        mInstance = this;
        if (companyModel != null) {
            reg_word_unit_type.setCenterTxt("流动人员");
            shearchCompanys.setCenterTxt(companyModel.getCompanyName());
            transactionModel.setTransactionCompanyId(companyModel.getCompanyId());
        }
        mListener = new RegTransactionListener(this, this);

    }

    @Override
    public void initEvents() {
        mToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                mInstance.finish();
            }
        });
        mRightToolbar.setLeftOnClick(new TToolbar.LeftOnClickListener() {
            @Override
            public void leftclick() {
                drawerManager();
            }
        });
        initDates();
        mRightMenu.setVisibility(View.VISIBLE);
        right_menu_unit_search_ll.setVisibility(View.GONE);
        right_menu_person_search_ll.setVisibility(View.GONE);
        right_menu_police_search_ll.setVisibility(View.GONE);
        right_menu_search_button.setVisibility(View.GONE);
        //左划菜单的Adapter
        mRightMenu.setAdapter(new CommonAdapter<CodeModel>(mInstance, mList,
                R.layout.right_menu_item) {
            @Override
            public void convert(final ViewHolder holder, final CodeModel model, int position) {
                holder.setText(R.id.right_menu_title, model.getValue());
            }
        });
        //左划菜单项点击事件
        mRightMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                drawerManager();
                reg_word_unit_type.setCenterTxt(mList.get(position).getValue());
                companyType = mList.get(position).getName();
                shearchCompanys.setCenterTxt("");//清空单位名称
                if (transactionModel != null) {
                    transactionModel.setTransactionCompanyId("");
                }
            }
        });
    }

    //加载数据
    private void initDates() {
        mList = new ArrayList<CodeModel>();
        mList = finalDb.findAllByWhere(CodeModel.class, "codeName='Code_CompanyType'");
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.reg_work_camera_btn://调用系统相机
                startCamera(11);
                break;
            case R.id.reg_work_reg_btn://生成事务
                if (!shearchCompanys.getCenterText().equals("")) {//单位信息已经选择
                    dialog = Utils.ProgressDialog(AddWorkActivity.this, dialog, "生成事务中，请稍候...", false);
                    dialog.show();
                    mListener.RegTransaction(transactionModel);
                } else {
                    mUtils.ToastShort("请选择单位信息");
                }
                break;
            case R.id.reg_word_unit_type:
                if (companyModel == null) {
                    drawerManager();
                }
                break;
            //选择单位点击时间
            case R.id.reg_work_companys:
                if (companyModel == null) {
                    Intent intent = new Intent();
                    intent.setClass(AddWorkActivity.this, ActivitySearchCompanyList.class);
                    intent.putExtra("CompanyType", companyType);
                    startActivityForResult(intent, 1);
                }
                break;
        }
    }

    //开启拍照
    public void startCamera(int type) {
        // 利用系统自带的相机应用:拍照
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        path = new StringBuffer();
        path.append(AddWorkActivity.this.getExternalFilesDir(null)).append("/IMG_CASH.jpg");
        File file = new File(path.toString());
        Uri uri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, type);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == -1) {
            if (requestCode == 11) {
                bm = Utils.getimage(this, path.toString());
                if (bm != null) {
                    mImg.setImageBitmap(bm);
                    mImg.setTag(bm);
                } else {
                    mImg.setImageResource(R.mipmap.person_header);
                    mImg.setTag(R.mipmap.person_header);
                }
            }
        }
        //接收选择的单位信息
        if (resultCode == 101) {
            com = (CompanyModel) data.getSerializableExtra("CompanyModel");
            shearchCompanys.setCenterTxt(com.getCompanyName());
            transactionModel.setTransactionCompanyId(com.getCompanyId());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 开启关闭左划菜单
     */
    private void drawerManager() {
        if (right_menu.isDrawerOpen(GravityCompat.END)) {
            right_menu.closeDrawer(GravityCompat.END);
        } else {
            right_menu.openDrawer(GravityCompat.END);
            mRightToolbar.setCenterTitle("选择人员类型");
        }
    }

    /**
     * 用于接收访问后台返回的数据
     *
     * @author 柳伟杰
     * created at 2016/2/17 10:06
     */
    @Override
    public void onRegTransactionResult(boolean isTrue, String mes, String id) {
        Utils.ToastShort(mInstance, mes);
        dialog.dismiss();
        if (isTrue) {
            if (!id.equals("0")) {
                Intent intent = new Intent();
                intent.setClass(AddWorkActivity.this, TransactionListActivity.class);
                Bundle b = new Bundle();
                if (companyModel != null) {
                    com = companyModel;
                }
                b.putSerializable("CompanyModel", com);
                intent.putExtras(b);
                intent.putExtra("TransactionId", id);
                startActivity(intent);
                this.finish();//关闭当前事务管理页面
            }
        }
    }

    /**
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (right_menu.isDrawerOpen(GravityCompat.END)) {//划出状态
                right_menu.closeDrawer(GravityCompat.END);
            } else {
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bm != null) {
            if (!bm.isRecycled()) {
                bm.recycle();//回收图片所占的内存
                System.gc();
            }
        }
    }
}
